package com.android.ddfafu.utils;

import com.android.ddfafu.result.Response;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UploadImageThead extends Thread{
    private static ObjectMapper MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    private File mImageFile;
    private String fileName;
    private String token;
    private String serverURL = Const.SERVER_URL_UPLOAD;
    private UploadImageListener mUploadImageListener;
    public UploadImageThead(File imageFile,String token,String username) {
        mImageFile = imageFile;
        this.token = token;
        String suffixName = imageFile.getName().substring(imageFile.getName().indexOf(".")+1);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String time = simpleDateFormat.format(new Date());
        String substring = username.substring(0, username.indexOf("@"));
        //图片命名为time.suffixName
        fileName = time+"_"+substring+"."+suffixName;

    }

    public void setUploadImageListener(UploadImageListener uploadImageListener){
        mUploadImageListener=uploadImageListener;
    }


    @Override
    public void run() {
        String resp = HttpUtil.postToUpload(serverURL, mImageFile, fileName, token);
        try {
            Response response = MAPPER.readValue(resp, Response.class);
            if (response.getCode() == 200){
                mUploadImageListener.uploadImageSuccess();
            }
            else {
                mUploadImageListener.uploadImageFail();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public interface UploadImageListener{
        void uploadImageFail();
        void uploadImageSuccess();
    }
}
